<?php

class Admin_ListaaprovacaoController extends App_Controller_Action
{

    private $_table     = 'LISTA_APROVACAO';
    private $_pk        = 'LAP_ID';
    private $_order_col = 'LAP_ID';
    private $_order     = 'DESC';
    private $_sta_col   = '';
    private $obj        = '';
    private $form       = '';
    public  $dir        = 'public/upload/listaaprovacao/';
    public  $_file_col  = 'LAP_FILE';
    
    public function init()
    {
        //if($this->getRequest()->getActionName() == 'edit') $this->form = new Admin_Form_Acessopaginas();
    }

    public function indexAction() {
        //$this->_helper->redirector('edit');
        
        Zend_Loader::loadClass('tools','library');
        Zend_Loader::loadClass('datetools','library');
        Zend_Loader::loadClass('elemform','library');
        Zend_Loader::loadClass('dominio','library');
        
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/validation/dist/jquery.validate.min.js');
        $this->view->headLink()->prependStylesheet($this->_urlbase.'/public/media/js/chosen/chosen.min.css'); 
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/chosen/chosen.jquery.min.js');

        $where = $this->_pk . ' > 0';
        
         
        $dtfiltro = $this->_getParam('dtfiltro', ''); 
        $cbfiltro = $this->_getParam('cbfiltro', ''); 
        $tpfiltro = $this->_getParam('tpfiltro', '1'); 
        
        if($dtfiltro != '') $where .= ' and LAP_DAT = "' .Datetools::dma_amd($dtfiltro).'"';
        //if($cbfiltro > '') $where .= ' and m.USU_ID = ' . $cbfiltro;
        //if($tpfiltro > '') $where .= ' and m.ACE_TPO = ' . $tpfiltro;
        
        $this->view->dtfiltro = $dtfiltro;
        $this->view->cbfiltro = $cbfiltro;
        $this->view->tpfiltro = $tpfiltro;
        
        
        $query = 'SELECT SQL_CACHE l.*,f.FAC_NOM FROM '.$this->_table.' l , FACULDADE f '
                . 'WHERE l.FAC_ID = f.FAC_ID AND '.$where.' '
                . 'ORDER BY '.$this->_order_col.' '.$this->_order;
        $result = $this->db->fetchAll($query);
        $this->view->result = $this->paginacao($result,20);
        
    }
    
    public function editAction() {
        
        Zend_Loader::loadClass('tools','library');
        Zend_Loader::loadClass('datetools','library');
        Zend_Loader::loadClass('imagem','library');
        Zend_Loader::loadClass('aluno','library');
        require_once($_SERVER['DOCUMENT_ROOT'] . "/library/excel_reader2.php");
        
        
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/validation/dist/jquery.validate.min.js');
        $this->view->headLink()->prependStylesheet($this->_urlbase.'/public/media/js/chosen/chosen.min.css'); 
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/chosen/chosen.jquery.min.js');
        
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/view/s_listaaprovacao.js?1='.rand(999,99988));
        
        //$this->view->form = $this->form;
        if($this->getRequest()->isPost()) {
            $formData = $this->getRequest()->getPost();
            try {
                if(1){//$this->form->isValid($formData)) {
                    $id = (int) $formData[$this->_pk]; //$this->form->getValue($this->_pk);
                    
                    $data = $formData; // $this->form->getValues();
                   
                    $returnImg = imagem::upload($this->_file_col,$this->dir,$id);
                    
                    unset($data['submit']);
                    unset($data['lista']);
                    unset($data['cursos']);
                    unset($data['exc_nom']);
                    
                    $data['FAC_ID'] = isset($data['FAC_ID'][0]) ? $data['FAC_ID'][0]:0;
                    $data['LAP_DAT'] = date('Y-m-d');
                    
                    if ($id == 0){
                        
                        if(strlen($_FILES[$this->_file_col]['tmp_name']) > 1){
                            $data['LAP_STA'] = 1;
                        }

                        $this->db->insert($this->_table,$data);
                        $id = $this->db->lastInsertId(); 
                        
                        imagem::rename($id,$this->dir,$returnImg['filenew']);
                        
                        $formData[$this->_pk] = $id;
                    }
                    else {
                        $this->db->update($this->_table,$data, $this->_pk.' = ' . $id);
                    }
                    
                    // upload do arquivo execel
                    if(strlen($_FILES[$this->_file_col]['tmp_name']) > 1){
                        $img = glob($this->dir.$id.'.*');
                        foreach($img as $filetemp) $filename = $filetemp;
                        
                        $excel = new Spreadsheet_Excel_Reader($filename);
                        //echo $data->dump(true,true);
                        
                        $totalLinhas = $excel->rowcount();
                        $totalColunas = $excel->colcount();
                        
                        $array = array();
                        for($i = 2; $i <= $totalLinhas; $i++) { // começa da linha 2
                            for ($j = 1; $j <= $totalColunas; $j++) {
                                    //$array  = $data->val($i, $j);
                                $array[$i][$j] = utf8_encode($excel->val($i, $j));
                            }
                        }                        
                        
                        $formData['FAC_ID'] = isset($formData['FAC_ID'][0]) ? $formData['FAC_ID'][0]:0;
                        $this->view->data = $formData;
                        $this->view->excel = $array;
                    }
                    // coluna 1 aluno, coluna 2 curso
                    
                    // grava alunos na tabela aprovações
                    if(isset($formData['lista'])){
                        
                        $img = glob($this->dir.$id.'.*');
                        foreach($img as $filetemp) $filename = $filetemp;
                        
                        $excel = new Spreadsheet_Excel_Reader($filename);
                        
                        //echo '<PRE>';print_r($formData['lista']);
                        $curso = '';
                        foreach($formData['lista'] as $key => $alu_id){
                            // echo $data->val($key, 1); // nome arquivo
                            
                            if(strlen($excel->val($key, 2)) > 3) $curso = $excel->val($key, 2);
                            // se veio a string do nome curso
                            else if(!is_int($formData['cursos'][$key])) $curso = $formData['cursos'][$key];
                            
                            // procura curso no cadastro
                            $CUF_ID = $this->verificarCurso($curso);
                            
                            // caso veio o curso so combobox selecionado
                            if($CUF_ID == 0 && is_int($formData['cursos'][$key])) 
                                $CUF_ID = $formData['cursos'][$key];
                            
                            $arr_apv = array(
                                'ALU_ID'  => $alu_id,
                                'FAC_ID'  => $data['FAC_ID'],
                                'CUF_ID'  => $CUF_ID,
                                'APV_ANO' => $data['LAP_ANO'],
                                'APV_SEM' => $data['LAP_SEM'],
                                'APV_CHM' => $data['LAP_CHM'],
                                'LAP_ID'  => $data['LAP_ID'],
                                'APV_DAT' => date('Y-m-d'),
                                'APV_EXCNOM' => $formData['exc_nom'][$key],
                            );
                            
                            $this->db->insert('APROVACAO',$arr_apv);

                        }
                        
                        // Lista finalizada
                        $this->db->update($this->_table,array('LAP_STA' => 2), $this->_pk.' = ' . $id);
                        
                        $this->_helper->redirector('index');
                    }
                    
                    // não foi selecionado nenhum item na lista e não possui upload arquivo. Edit update 
                    if( (!isset($formData['lista']) && strlen($_FILES[$this->_file_col]['tmp_name']) < 1) || (strlen($_FILES[$this->_file_col]['tmp_name']) > 1 && $id > 0) ){
                        $urlOptions = array('controller'=>$this->_controller,'action'=>'edit','id'=>$id);
                        $this->_helper->redirector->gotoRoute($urlOptions);
                    }
                    
                    //$this->_helper->redirector('index');
                } else {
                    //$this->form->populate($formData);
                    $this->view->data = $data;
                }
            } catch(Exception $ex) {
                Zend_Loader::loadClass('errordb','library');
                echo '<script>alert("'.$ex->getMessage().'");</script>';
                // echo $ex->getMessage();
                //$this->form->populate($formData);
                $this->view->data = $data;
            }
        } else {
            $id = $this->_getParam('id', 0);
            if ($id > 0) {
                $query = 'SELECT SQL_CACHE * FROM '.$this->_table.' WHERE '.$this->_pk . ' = ' . $id;
                $data = $this->db->fetchRow($query);
                //$this->form->populate($data);
                $this->view->data = $data;
                
                
                $query = 'SELECT SQL_CACHE CUF_ID,CUF_NOM FROM CURSOFACULDADE WHERE CUF_STA = 1';
                $this->view->cursos = $this->db->fetchAll($query);
                
                
                $this->view->excel = array();
                
                $lista = array();
                if($data['LAP_STA'] > 0){
                    $query = 'SELECT SQL_CACHE a.ALU_NOM, c.CUF_NOM FROM APROVACAO p, ALUNO a, CURSOFACULDADE c '
                            . ' WHERE p.'.$this->_pk . ' = ' . $id
                            . ' AND p.ALU_ID = a.ALU_ID'
                            . ' AND p.CUF_ID = c.CUF_ID';
                    $lista = $this->db->fetchAll($query);
                    
                    
                    $img = glob($this->dir.$id.'.*');
                    foreach($img as $filetemp) $filename = $filetemp;

                    $excel = new Spreadsheet_Excel_Reader($filename);
                    //echo $data->dump(true,true);

                    $totalLinhas = $excel->rowcount();
                    $totalColunas = $excel->colcount();

                    $array = array();
                    for($i = 2; $i <= $totalLinhas; $i++) { // começa da linha 2
                        for ($j = 1; $j <= $totalColunas; $j++) {
                                //$array  = $data->val($i, $j);
                            $array[$i][$j] = utf8_encode($excel->val($i, $j));
                        }
                    }                        

                    $formData['FAC_ID'] = isset($formData['FAC_ID'][0]) ? $formData['FAC_ID'][0]:0;
                    $this->view->excel = $array;
                    
                    
                    
                }
                $this->view->lista = $lista;
                
            }
        }
    }

    public function deleteAction() {
        $this->_helper->layout->disableLayout(); 
        $this->_helper->viewRenderer->setNoRender();  
        $ok = FALSE;
        $id = $this->_getParam('id', 0);
        if ((int)$id > 0 ) {   
            //$data = array($this->_sta_col => 0);
            //$ok = (bool) $this->obj->update($data, $this->_pk . ' = ' . $id);
            
            $ok = (bool) $this->db->delete('APROVACAO',$this->_pk . ' = ' . $id);
            
            $ok = (bool) $this->db->delete($this->_table,$this->_pk . ' = ' . $id);
            
            foreach (glob($this->dir.$id.'.*') as $file) {
                unlink($file);
            }
            
        }       
        echo json_encode(array('ok' => $ok));
    }
    
    public function verificarCurso($curso) {
        
        Zend_Loader::loadClass('tools','library');
        
        $curso = utf8_encode($curso); // erro codificação arquivo por isso utf8_encode
        
        $t_curso = trim($curso);
        
        $CUF_ID = 0;
        
        if(strlen($t_curso) > 1){
        
            $query = 'SELECT SQL_CACHE CUF_ID FROM CURSOFACULDADE WHERE CUF_NOM LIKE "%'.$t_curso.'%"';
            $result = $this->db->fetchRow($query);

            if($result['CUF_ID'] > 0){
                $CUF_ID = $result['CUF_ID']; 
            }else{
                $data = array('CUF_NOM' => $curso, 'CUF_STA' => 1);
                $this->db->insert('CURSOFACULDADE',$data);
                $CUF_ID = $this->db->lastInsertId(); 
            }
        }
        
        return $CUF_ID;
        
    }
    
    public function removelistaalunoAction(){
        
        $this->_helper->layout->disableLayout(); 
        $this->_helper->viewRenderer->setNoRender();  
        $ok = FALSE;
        $lap_id = $this->_getParam('lap_id', 0);
        $apv_id = $this->_getParam('apv_id', 0);
        $alu_id = $this->_getParam('alu_id', 0);
        if($apv_id > 0 && $alu_id > 0) { 
            
            $ok = (bool) $this->db->delete('APROVACAO','LAP_ID = '.$lap_id.' AND APV_ID = '.$apv_id.' AND ALU_ID = '.$alu_id);
        }
        
        echo json_encode(array('ok' => $ok));
        
    }
    
    public function aprovadosAction(){
        
        $this->view->titulo = 'Lista de Alunos Aprovados';
        
        Zend_Loader::loadClass('aluno','library');
        Zend_Loader::loadClass('dominio','library');
        
        $id = $this->_getParam('id', 0);
        
        $filtro_nm = $this->_getParam('filtro_nm', '');
        
        if($filtro_nm != '') $where .= ' AND u.ALU_NOM like "' . trim($filtro_nm) .'%" ';
        
        $this->view->filtro_nm = $filtro_nm;
        
        
        $query = 'SELECT SQL_CACHE a.APV_ANO, a.APV_SEM, a.APV_CHM, a.ALU_ID, '
                .' l.*, u.ALU_NOM, f.FAC_NOM, c.CUF_NOM'
                .' FROM LISTA_APROVACAO l, APROVACAO a, ALUNO u, FACULDADE f, CURSOFACULDADE c '
                .' WHERE l.LAP_ID = '.$id.' '.$where
                .' AND l.LAP_ID = a.LAP_ID AND a.ALU_ID = u.ALU_ID'
                .' AND a.FAC_ID = f.FAC_ID AND a.CUF_ID = c.CUF_ID'
                .' ORDER BY u.ALU_NOM ASC';
        $result = $this->db->fetchAll($query);
        $this->view->result = $this->paginacao($result,20);
    }
    

}